package com.bf.hotpoint.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.bf.hotpoint.domain.SimpleUser;
import com.bf.hotpoint.domain.User;
import com.bf.hotpoint.enums.KeyOfJsonResultEnum;
import com.bf.hotpoint.enums.ResultCodeEnum;
import com.bf.hotpoint.service.CommonService;
import com.bf.hotpoint.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	static Logger log = Logger.getLogger(UserController.class.getName());

	@Autowired
	private UserService userService;
	
	@Autowired
	private CommonService commonService;


	@RequestMapping(value="/print/{uuid}",method= {RequestMethod.POST,RequestMethod.GET})
	public MappingJackson2JsonView print(@PathVariable String uuid){		
		User user = userService.printUser(uuid);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(KeyOfJsonResultEnum.SIMPLE_USER.getKey(), user);
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(result);
		return view;
	}
	
	@RequestMapping(value="/inituser",method= {RequestMethod.POST,RequestMethod.GET})
	public MappingJackson2JsonView initDevicePost(
			@RequestParam("uuid") String uuid,
			@RequestParam("deviceToken") String deviceToken
			){		
		ResultCodeEnum codeValue = userService.initUser(uuid,deviceToken);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(KeyOfJsonResultEnum.CODE.getKey(), codeValue.ordinal());
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(result);
		return view;
	}
	
	
	//保存用户信息
	@RequestMapping(value="/savesimpleuser",method= {RequestMethod.POST,RequestMethod.GET})
	public MappingJackson2JsonView saveSimpleUser(
			@RequestParam("uuid") String uuid,
			@RequestParam(value = "nickname", required = false) String nickName,
			@RequestParam(value = "image", required = false) MultipartFile image,
			@RequestParam(value = "sex", required = false) boolean sex
			){
		ResultCodeEnum codeValue = ResultCodeEnum.SUCCESS; 
		try {
			//删除硬盘上的照片
			File file = new File(this.findPathOfHeadImage(uuid + ".jpg"));
    		if(file.delete()){
    			log.info("user head uuid:"+uuid+" already is deleted");
    		}else{
    			System.out.println("Delete operation is failed.");
    		}
			if (image != null) {
				//保存用户头像
				this.uploadFileHandler(uuid, image);
				log.info("user head uuid:"+uuid+" already is uploaded");
			}
			userService.saveUserToMongo(uuid,nickName,sex);	
		} catch (Exception e) {
			log.error(e);
		}
				
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(KeyOfJsonResultEnum.CODE.getKey(), codeValue.ordinal());
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(result);
		return view;
	}
	
	//获取用户信息
	@RequestMapping(value="/getsimpleuser",method= {RequestMethod.POST,RequestMethod.GET})
	public MappingJackson2JsonView getSimpleUser(@RequestParam("uuid") String uuid){		
		SimpleUser user = userService.getUserFromMongo(uuid);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(KeyOfJsonResultEnum.SIMPLE_USER.getKey(), user);
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(result);
		return view;
	}
	
	public String findPathOfHeadImage(String name)
	{
		// Creating the directory to store file
		String rootPath = System.getProperty("catalina.home");
		File dir = new File(rootPath + File.separator + "userheads");
		if (!dir.exists())
			dir.mkdirs();
		return dir.getAbsolutePath()
				+ File.separator + name;
	}

	/**
	 * Upload single file using Spring Controller
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public @ResponseBody String uploadFileHandler(
			@RequestParam("name") String name,
			@RequestParam("file") MultipartFile file) {

		if (!file.isEmpty()) {

			String fileName = file.getOriginalFilename(); // get filename on
															// client's machine
			String contentType = file.getContentType(); // get content type, you
														// can recognize which
														// kind of file is, pdf
														// or image or doc etc
			long size = file.getSize(); // get file size in bytes
			
			if(contentType == null)
			{
				return null;
			}
			
			if(MediaType.IMAGE_PNG_VALUE.equals(contentType))
			{
				name = name+".png";
			}else if(MediaType.IMAGE_JPEG_VALUE.equals(contentType)){
				name = name+".jpg";
			}else if(MediaType.IMAGE_GIF_VALUE.equals(contentType)){
				name = name+".gif";
			}

			try {
				byte[] bytes = file.getBytes();

				// Create the file on server
				File serverFile = new File(this.findPathOfHeadImage(name));
				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();

				log.info("Server File Location=" + serverFile.getAbsolutePath());
				log.info("You successfully uploaded file=" + name);

				return serverFile.getAbsolutePath();
			} catch (Exception e) {
				log.error("You failed to upload " + name + " => "
						+ e.getMessage());
			}
		} else {
			log.info("You failed to upload " + name
					+ " because the file was empty.");
			return null;
		}
		return null;
	}
	
	//获取用户头像
	@RequestMapping(value = "/getuserheadphoto", method = { RequestMethod.POST })
	public MappingJackson2JsonView getUserHeadPhoto(
			@RequestParam("uuid") String uuid) {
		byte[] image = null;
		
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		Map<String, Object> result = new HashMap<String, Object>();
		ResultCodeEnum resultCode = ResultCodeEnum.SUCCESS;
		
		try {
			image = this.extractBytes(this.findPathOfHeadImage(uuid+".jpg"));
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
			result.put(KeyOfJsonResultEnum.CODE.getKey(), ResultCodeEnum.HAS_NO_IMAGE);
			view.setAttributesMap(result);
			return view;
		}

		if (image == null) {
			log.info("can't find image by name:" + uuid +".png");
			result.put(KeyOfJsonResultEnum.CODE.getKey(), ResultCodeEnum.HAS_NO_IMAGE);
			view.setAttributesMap(result);
			return view;
		}

		result.put("image", new String (Base64.encodeBase64(image)));
		result.put(KeyOfJsonResultEnum.CODE.getKey(), resultCode);
		view.setAttributesMap(result);
		return view;
	}
	
	public byte[] extractBytes(String path) throws IOException {
		// open image
		File file = new File(path);
		
		byte[] bFile = new byte[(int) file.length()];
		FileInputStream fileInputStream=null;
	     try {
	            //convert file into array of bytes
		    fileInputStream = new FileInputStream(file);
		    fileInputStream.read(bFile);
		    fileInputStream.close();

        }catch(Exception e){
        	e.printStackTrace();
        }
        return bFile;
	}
	
}
